#pragma once

#include <iostream>

#include <sys/epoll.h>

#include "log.hpp"

static const int defaultFd = -1;
static const int gsize = 128;

class Epoller
{
public:
    Epoller() : _epfd(defaultFd)
    {
    }
    void Create()
    {
        _epfd = epoll_create(gsize);
        if (_epfd < 0)
        {
            logMessage(FATAL, "epoll create error: %s", strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }
    bool Control(int sock, uint32_t event, int action)
    {
        int n = 0;
        if (action == EPOLL_CTL_MOD)
        {
            struct epoll_event ev;
            ev.events = event;
            ev.data.fd = sock;
            n = epoll_ctl(_epfd, action, sock, &ev);
        }
        else if (action == EPOLL_CTL_DEL)
        {
            n = epoll_ctl(_epfd, action, sock, nullptr);
        }
        else n = -1;

        return n == 0;
    }
    bool AddEvent(int sock, uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sock;

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sock, &ev);
        return n == 0;
    }
    int Wait(struct epoll_event revs[], int num, int timeout)
    {
        int n = epoll_wait(_epfd, revs, num, timeout);
        return n;
    }
    int getEpfd()
    {
        return _epfd;
    }
    ~Epoller()
    {
        if (_epfd != defaultFd)
            close(_epfd);
    }

private:
    int _epfd;
};